package com.hkd.forum.service.impl;

import com.hkd.forum.common.AppResult;
import com.hkd.forum.common.ResultCode;
import com.hkd.forum.dao.ArticleMapper;
import com.hkd.forum.exception.ApplicationException;
import com.hkd.forum.model.Article;
import com.hkd.forum.model.Board;
import com.hkd.forum.model.User;
import com.hkd.forum.service.IArticleService;
import com.hkd.forum.service.IBoardService;
import com.hkd.forum.service.IUserService;
import com.hkd.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        //非空校验
        if(article == null
                || article.getUserId() == null
                || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())

        ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setVisitCount(0);//访问数
        article.setReplyCount(0);//回复数
        article.setLikeCount(0);//点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //插入数据
        int articleRow = articleMapper.insertSelective(article);
        if(articleRow <= 0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //更新用户发帖数
        User user = userService.selectById(article.getUserId());
        //没有找到指定用户信息
        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败 userId = "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());

        //获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        //判断是否有板块
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ",发帖失败 boardId = "+article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块中帖子数量
        boardService.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString()+" userId = "+article.getUserId()+
                " boardId = "+article.getBoardId()+" articleId = "+article.getId()+" 发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if(boardId == null ||boardId <= 0 ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用dao查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId == null || userId <= 0 ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用dao查询
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;

    }

    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if( id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectDetailById(id);

        //判断结果是否为空
        if(article == null ){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新文章的访问数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //保存数据库，调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //判断结果
        if(row != 1){
            //打印日志
            log.warn(ResultCode.FAILED_UPDATE_ARTICLE_VISIT_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE_ARTICLE_VISIT_COUNT));
        }
        //返回帖子详情 数据库更新但是对象本身还没变
        article.setVisitCount(article.getVisitCount() + 1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if( id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectByPrimaryKey(id);
        //返回结果
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null || id < 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        //保存数据库，调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //判断结果
        if(row!= 1){
            //打印日志
            log.warn(ResultCode.FAILED_UPDATE_ARTICLE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE_ARTICLE));
        }
        log.info(ResultCode.SUCCESS.toString()+" userId = "+id+" boardId = "+id+" articleId = "+id+" 文章修改成功");

    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if( id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //判断结果
        if(row!= 1){
            //打印日志
            log.warn(ResultCode.FAILED_UPDATE_ARTICLE_LIKE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE_ARTICLE_LIKE_COUNT));
        }
        log.info(ResultCode.SUCCESS.toString()+" userId = "+id+" boardId = "+id+" articleId = "+id+" 文章点赞成功");
    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if( id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);

        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info(ResultCode.SUCCESS.toString()+" userId = "+id+" boardId = "+id+" articleId = "+id+" 文章删除成功");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if( id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //判断结果
        if(row!= 1){
            //打印日志
            log.warn(ResultCode.FAILED_UPDATE_ARTICLE_REPLY_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE_ARTICLE_REPLY_COUNT));
        }
        log.info(ResultCode.SUCCESS.toString()+" userId = "+id+" boardId = "+id+" articleId = "+id+" 文章添加回复成功");
    }
}
